<?php
/**
 * Created by PhpStrom
 * User: fei.song
 * Date: 2021/4/27 10:47
 * Desc:
 */

namespace App\Service;


use App\Lib\Logger;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Org;
use App\Models\Admin\Setting;
use App\Models\Admin\Site;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class SiteService extends BaseService {
    /**
     * @var string 站点设置缓存KEY
     */
    protected $cachePrefix = 'SITE_CONFIG_';

    /**
     * @var float|int 缓存有效期
     */
    protected $ttl = 60 * 60 * 24 * 5;//5天

    /**
     * 获取全部站点
     * @return array
     */
    public function getSiteLIst() {
        return Site::orderBy('id', 'desc')->get()->toArray();
    }

    /**
     * 通过ID获取站点信息
     * @param int $id 站点ID
     * @return mixed
     */
    public function getSiteById($id) {
        return Site::find($id)->toArray();
    }

    /**
     * 新增站点
     * @param $site
     * @return mixed
     */
    public function add($site) {
        $data = [
            'name' => $site['name'],
            'status' => $site['status'],
            'expire_at' => strtotime($site['expire_at'])
        ];
        $site = (new Site())->create($data)->toArray();
        $this->log(Logger::LOG_LEVEL_INFO,Logger::SITE,'create',"新增站点[ID:".$site['id']."],成功",$site);
        //站点初始化
        $this->siteInit($site);
        return $site;
    }

    /**
     * 编辑站点
     * @param $id
     * @param $site
     * @return mixed
     */
    public function update($id, $site) {
        $data = [
            'name' => $site['name'],
            'status' => $site['status'],
            'expire_at' => strtotime($site['expire_at'])
        ];
        $site = Site::where("id", $id)->update($data);
        $this->log(Logger::LOG_LEVEL_INFO,Logger::SITE,'update',"修改站点[ID:{$id}],成功",$site);
        return $site;
    }

    /**
     * 获取站点配置
     * @param null $key
     * @param null $default
     * @return array|\ArrayAccess|mixed
     */
    public function config($key = null, $default = null) {
//        if (is_array($key)) {
//            return $this->set($key);
//        }
        $config = $this->get();

        if (is_null($key)) {
            return $config;
        }

        return Arr::get($config, $key, $default);
    }

    /**
     * 重新缓存
     * @param null $siteId
     */
    public function cache($siteId = null) {
        $this->set($siteId);
    }

    private function cacheKey() {
        return $this->cachePrefix . getCurrentSiteId();
    }

    /**
     * 缓存设置
     * @param null $siteId
     * @return mixed
     */
    private function set($siteId = null) {
        $config = (new SettingService())->getAllBySiteId($siteId);
        $config = array_column($config, 'value', 'name');
        if ($siteId) {
            $cacheKey = $this->cachePrefix . $siteId;
        } else {
            $cacheKey = $this->cacheKey();
        }
        Cache::put($cacheKey, $config, $this->ttl);
        return $config;
    }

    /**
     * 获取缓存
     * @return mixed
     */
    private function get() {
        $config = Cache::get($this->cacheKey());
        if (!$config) {
            $config = $this->set();
        }
        return $config;
    }

    /**
     * 获取select站点信息
     */
    public function getSelect() {
        return (new Site())->get(["id", "name"]);
    }

    private function siteInit($site) {
        //添加站点管理员角色
        //添加站点管理员
//        $randomStr= Str::random(6);
        $user=(new AdminUser())->find(2)->replicate();
        $name='admin'.$site['id'];
        $user->name=$name;
        $user->email=$name.'@'.config('app.name');
        $user->site_id=$site['id'];
        $user->save();
        $user->fresh();
        $authService=new AuthService();
        $role=$authService->getOne(2);
        $user->assignRole($role);

        //添加组织机构
        $org=[
            'name' => '全站',
            'site_id' => $site['id'],
            'code' => $site['id'].'.',
        ];
        $org=(new Org())->create($org);
//        $org->code=$org->id.'.';
//        $org->save();

        // todo 添加全局设置
        /*$set=[
            [
                'name' => 'site',
                'value'=>[

                ]
            ]
        ];
        $set=(new Setting())->create($set);*/
    }

    /**
     * 获取单站点信息
     */
    public function getInfo($id) {
        return (new Site())->find($id)->toArray();
    }
}
